<?php

class PortfolioController extends Backend_Base_Controller
{


    public function indexAction()
    {

    }

    public function ajaxlistAction()
    {

        $language = Zend_Registry::get('language');
        $db       = Zend_Registry::get('db');
        $request  = $this->getRequest();

        $page  = $request->getParam('page') ? intval($request->getParam('page')) : 1;
        $limit = $request->getParam('rows') ? intval($request->getParam('rows')) : 10;
        $sidx  = $request->getParam('sidx') ? $request->getParam('sidx')         : 1;
        $sord  = $request->getParam('sord') ? $request->getParam('sord')         : 'DESC';

        $select = $db->select()->from(array('p' => 'portfolio'));
        $select->join(array('pl' => 'portfolio_local'), 'pl.portfolio_id = p.id');
        $select->where('pl.language_id = ?', $language->getId());
        $select->order("$sidx $sord");
        $stmt   = $db->query($select);
        $result = $stmt->fetchAll();
        $count  = count($result);

        if ($count >0)
        {
            $total_pages = ceil($count / $limit);
        } else {
            $total_pages = 0;
        }

        if ($page > $total_pages)
        {
            $page = $total_pages;
        }

        $responce = array(
            'page'    => $page,
            'total'   => $total_pages,
            'records' => $count,
            'rows'    => array()
        );
        $start = $limit * $page - $limit;

        $j = 0;
        for ($i = 0; $i < count($result); $i++)
        {
            if ($i >= $start && $i < $start + $limit)
            {
                $allow_edit   = true;
                $allow_delete = true;
                $allow_use    = !empty($result[$i]['enabled']);

                $editUrl   = $this->_helper->url('edit', 'portfolio', null, array('id' => $result[$i]['id']));
                $deleteUrl = $this->_helper->url('delete', 'portfolio', null, array('id' => $result[$i]['id']));

                $responce['rows'][$j]['id']   = $result[$i]['id'];
                $responce['rows'][$j]['cell'] = array(
                    $result[$i]['id'],
                    $result[$i]['code'],
                    $result[$i]['icon'] ? '<img src="/media/portfolio/tiny/'.$result[$i]['icon'].'" />' : '',
                    $result[$i]['title'],
                    '<input type="checkbox" readonly="readonly" disabled="disabled"' . ($allow_use ? ' checked="checked"' : '') . ' />',
                    ($allow_edit   ? '<a href="' . $editUrl . '">' . $this->view->translate('Edit') . '</a>|' : '') .
                    ($allow_delete ? '<a href="'.$deleteUrl.'">'.$this->view->translate('Delete').'</a>' : '')
                );
                $j++;
            }
        }

        echo json_encode($responce);
        die();
    }

    public function editAction()
    {
        $request          = $this->getRequest();
        $languages        = Application_Model_Language::getList();
        $id               = intval($request->getParam('id'));
        $form             = new Application_Form_Edit_Portfolio($id);
        $post             = array();
        $translation_keys = array(
            'title'       => 'title_',
            'description' => 'description_'
        );

        if ($id)
        {
            $entity_dbtable = new Application_Model_DbTable_Portfolio();
            $model          = $entity_dbtable->find($id)->current();
            if (!empty($model) && $model->id)
            {
                $post['enabled'] = $model->enabled;
                $post['code']    = $model->code;

                $translation_dbtable = new Application_Model_DbTable_PortfolioLocal();
                $translations = $translation_dbtable->fetchAll('portfolio_id = ' . $id);

                if (!empty($translations))
                {
                    foreach ($translations as $translation)
                    {
                        if (!empty($translation))
                        {
                            $lid = $translation->language_id;
                            foreach ($translation_keys as $column => $prefix)
                            {
                                if ($translation->__get($column))
                                {
                                    $post[$prefix.$lid] = $translation->__get($column);
                                }
                            }
                        }
                    }
                }
            }
        }

        if ($request->getPost())
        {
            $post = $request->getPost();
        }

        $form->setDefaults($post);

        if ($post && !empty($_POST))
        {
            if ($form->isValid($post))
            {

                $form_data         = $form->getValues();
                $translations_data = array();
                $entity_data       = array(
                    'code'    => $form_data['code'],
                    'enabled' => $form_data['enabled']
                );

                if ($form->getElement('icon')->isUploaded())
                {
                    if ($form->getElement('icon')->receive())
                    {
                        $extension = pathinfo($form->getElement('icon')->getValue(), PATHINFO_EXTENSION);
                        $filename  = $form->getElement('icon')->getValue();
                        $tmpdir    = getcwd() . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
                        $destdir   = realpath(getcwd() . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'portfolio');
                        $imgpath   = $tmpdir . $filename;
                        $finalname = uniqid() . '.' . $extension;

                        if (!empty($model->icon)) {
                            foreach (array('medium', 'small', 'tiny', 'original') as $size) {
                                if (file_exists($destdir . DIRECTORY_SEPARATOR . $size . DIRECTORY_SEPARATOR . $model->icon))
                                {
                                    @unlink($destdir . DIRECTORY_SEPARATOR . $size . DIRECTORY_SEPARATOR . $model->icon);
                                }
                            }
                        }

                        if (file_exists($imgpath))
                        {
                            $image     = new Zend_Image($imgpath, new Zend_Image_Driver_Gd());
                            $transform = new Zend_Image_Transform($image);

                            if ($image->getWidth() > $image->getHeight())
                            {
                                $transform->fitToWidth(300)->save($destdir . DIRECTORY_SEPARATOR . 'medium' . DIRECTORY_SEPARATOR . $finalname);
                                $transform->fitToWidth(147)->save($destdir . DIRECTORY_SEPARATOR . 'small' . DIRECTORY_SEPARATOR . $finalname);
                                $transform->center()->middle()->crop(74, 74)->save($destdir . DIRECTORY_SEPARATOR . 'tiny' . DIRECTORY_SEPARATOR . $finalname);
                            } else {
                                $transform->fitToHeight(300)->save($destdir . DIRECTORY_SEPARATOR . 'medium' . DIRECTORY_SEPARATOR . $finalname);
                                $transform->fitToWidth(147)->save($destdir . DIRECTORY_SEPARATOR . 'small' . DIRECTORY_SEPARATOR . $finalname);
                                $transform->center()->middle()->crop(74, 74)->save($destdir . DIRECTORY_SEPARATOR . 'tiny' . DIRECTORY_SEPARATOR . $finalname);
                            }

                            copy($imgpath, $destdir . DIRECTORY_SEPARATOR . 'original' . DIRECTORY_SEPARATOR . $finalname);
                        }

                        $entity_data['icon'] = $finalname;
                    }
                }

                foreach ($languages as $language)
                {
                    $lid     = $language->getId();
                    $lvalues = array();
                    foreach ($translation_keys as $dbkey => $prefix)
                    {
                        $rkey = $prefix . $lid;
                        if (isset($form_data[$rkey]))
                        {
                            $lvalues[$dbkey] = $form_data[$rkey];
                        }
                    }
                    if (!empty($lvalues))
                    {
                        $translations_data[$lid] = $lvalues;
                    }
                }

                $entity_dbtable = new Application_Model_DbTable_Portfolio();
                if ($id > 0)
                {
                    $entity_dbtable->update($entity_data, "id=$id");
                } else {
                    $id = $entity_dbtable->insert($entity_data);
                }

                $translation_dbtable = new Application_Model_DbTable_PortfolioLocal();
                $translation_dbtable->delete("portfolio_id = $id");

                foreach ($translations_data as $lid => $lvalues)
                {
                    $lvalues['portfolio_id'] = $id;
                    $lvalues['language_id'] = $lid;
                    $translation_dbtable->insert($lvalues);
                }

                $this->_helper->message($this->view->translate('Changes were successfully saved!'), Backend_Flash_Messenger::TYPE_SUCCESS);
                $redirector = new Zend_Controller_Action_Helper_Redirector;
                $redirector->gotoUrl('/portfolio/index')->redirectAndExit();
            } else {
                $this->_helper->message($this->view->translate('Error saving data: invalid input!'), Backend_Flash_Messenger::TYPE_ERROR);
            }
        }

        $this->view->form      = $form;
        $this->view->id        = $id;
        $this->view->data      = $form->getValues();
        $this->view->languages = $languages;
    }

    public function deleteAction()
    {
        $request             = $this->getRequest();
        $language            = Zend_Registry::get('language');
        $id                  = intval($request->getParam('id'));
        $language_id         = $language->getId();
        $confirmed           = $request->getParam('confirmed');
        $redirector          = new Zend_Controller_Action_Helper_Redirector;
        $entity_dbtable      = new Application_Model_DbTable_Portfolio();
        $translation_dbtable = new Application_Model_DbTable_PortfolioLocal();
        $confirmUrl          = $this->_helper->url('delete', 'portfolio', null, array('id' => $id, 'confirmed' => 'true'));
        $cancelUrl           = $this->_helper->url('index', 'portfolio');

        if ($confirmed && $id)
        {
            $model   = $entity_dbtable->find($id)->current();
            $destdir = realpath(getcwd() . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'portfolio');
            if (!empty($model->icon))
            {
                foreach (array('medium', 'small', 'tiny', 'original') as $size)
                {
                    if (file_exists($destdir . DIRECTORY_SEPARATOR . $size . DIRECTORY_SEPARATOR . $model->icon))
                    {
                        @unlink($destdir . DIRECTORY_SEPARATOR . $size . DIRECTORY_SEPARATOR . $model->icon);
                    }
                }
            }

            $entity_dbtable->delete("id = $id");
            $this->_helper->message($this->view->translate('Action was successfully performed!'), Backend_Flash_Messenger::TYPE_SUCCESS);
            $redirector->gotoUrl('/portfolio/index')->redirectAndExit();
        }

        $select      = $translation_dbtable->select()->where('portfolio_id = ?', $id)->where('language_id = ?', $language_id);
        $translation = $translation_dbtable->fetchRow($select);

        if ($translation->title)
        {
            $this->view->name       = $translation->title;
            $this->view->cancelUrl  = $cancelUrl;
            $this->view->confirmUrl = $confirmUrl;
        } else {
            $redirector->gotoUrl('/portfolio/index')->redirectAndExit();
        }
    }
}

